<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-06 20:33:49
 * @desc  支付宝支付类
 */
namespace app\index\controller;
use think\Controller;
use think\Config;
use think\Model;
use think\Db;
use think\Request;
use alipay\Pagepay;
use app\comm\service\AlipayService;
class Alipay extends Controller{
	/**
	 * 支付宝支付参数
	 * @Author   lingyun
	 * @DateTime 2017-12-06T20:36:45+0800
	 * @return   [type]                   [description]
	 */
	public function pay(){
	    $root = request()->domain();        //网站更目录
		$post = input('param.');			//接受的参数
		$this->checkorder($post);		//检验订单状态
        $order = db('order')->where('order_sn',$post['order_sn'])->find();
        $params = array(
			'out_trade_no'=>$order['order_sn'],
			'subject'=>'订单支付',
			'total_amount'=>$order['final_amount']
//			'total_amount'=>0.01
		);
		$config = config('alipay');     //修改支付宝的回调url地址
        $config['notify_url'] = $root."/index.php/index/notify/notifyalipay";
		Pagepay::pay($params,$config);
	}
	/**
	 * 回调地址
	 * @Author   lingyun
	 * @DateTime 2017-12-12T16:17:17+0800
	 * @return   [type]                   [description]
	 */
	public function notify(){
		$request = input('post.');
		$dir = 'public/notify';
		if (!file_exists($dir)){
            mkdir ($dir,0777,true);
        }
        $json = time().'.json';
		$service = new AlipayService();
		$result = $service->init();
		if($result['code'] == 1){
			$this->success('支付成功',url('Index/index'));
		}else{
			$this->error($result['msg'],url('Index/index'));
		}
	}

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 支付宝
     * 2018-03-21
     */
	public function recharge(){
        $root = request()->domain();        //网站更目录
        $post = input('param.');
        //预支付检查订单
        $flag = $this->check_recharge_order($post);
        if($flag['status'] == 0){       //订单失败
            $this->assign('msg',$flag['msg']);
            $this->assign('title','重新充值');
            $this->assign('url',url('User/recharge'));

            return $this->fetch('public/error');
        }
        $order = db('user_wallet_log')->where('order_sn',$post['order_sn'])->find();
//        $post['final_amount'] = $post['amount'];
//        $data = array(
//            'uid'=>$post['uid'],
//            'admin_id'=>0,
//            'store_id'=>0,
//            'order_id'=>0,
//            'order_sn'=>$post['order_sn'],
//            'pay_status'=>0,
//            'pay_type'=>$post['pay_type'],
//            'amount'=>$post['amount'],
//            'sign'=>2,
//            'chargetype'=>1,
//            'charge_cn'=>"会员充值",
//            'addtime'=>time()
//        );
//        Db::name('user_wallet_log')->insert($data);
//        $result = $this->checkRechargeOrder($post);
//        if ($result["status"] == 0) {
//            $this->error($result["msg"]);
//        }
//        $post = input('param.');			//接受的参数
//        $this->checkorder($post);		//检验订单状态
//        $order['amount'] = 0.01;
        $params = array(
            'out_trade_no'=>$order['order_sn'],
            'subject'=>'会员充值',
            'total_amount'=>$order['amount']
        );
        $config = config('alipay');     //修改支付宝的回调url地址
        $config['notify_url'] = $root."/index.php/index/notify/notifyalirecharge";
        $config['return_url'] = $root."/index.php/index/user/recharge";

        Pagepay::pay($params,$config);
    }


	/**
	 * 检查订单信息
	 * @Author   lingyun
	 * @DateTime 2017-12-12T19:59:54+0800
	 *
	 */
	private function checkorder($param){
		if(empty($param['order_sn'])){
            $this->assign('err_msg','找不到订单信息，请重新购买商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','购买其它商品');
            return $this->fetch('public/error');
            exit();
        }
		$order = Db::name('order')->where('order_sn',$param['order_sn'])->find();
		if($order['pay_status'] == 1){
            $this->assign('err_msg','该订单已经支付，请勿重复支付');
            $this->assign('err_url',url('User/index'));
            $this->assign('err_button','查看订单');
            return $this->fetch('public/error');
            exit();
//			$this->error('该订单已经支付，请勿重复支付',url('Index/index'));
		}else{
			$cur_time = time()-30*60;
			if($order['addtime']<$cur_time){
			    $order = db('order')->where('order_sn',$param['order_sn'])->find();
			    db('order')->where('order_sn',$param['order_sn'])->update(['order_status'=>8]);
			    db('order_details')->where('order_id',$order['id'])->update(['status'=>8]);
			    db('order_action')->insert(['uid'=>$order['uid'],'order_id'=>$order['id'],'action_user'=>0,'order_status'=>8,'pay_status'=>0,'status_desc'=>'交易已关闭','storeid'=>$order['store_id'],'addtime'=>time()]);
                $this->assign('err_msg','订单已过期，不能发起支付');
                $this->assign('err_url',url('User/index'));
                $this->assign('err_button','查看订单');
                return $this->fetch('public/error');
                exit();
//				$this->error('订单已过期，不能发起支付',url('Index/index'));
			}
		}
	}

    /**
     * @Author lignyun
     * @Desc    检查会员充值订单
     * @param   $post   提交信息
     * 2018-03-21
     */
	private function checkRechargeOrder($post){
        if(empty($post['id'])){
            $this->assign('err_msg','找不到订单信息,请重新充值');
            $this->assign('err_url',url('User/recharge'));
            $this->assign('err_button','重新充值');
            return $this->fetch('public/error');
            exit();
        }else{
            $order = Db::name('user_wallet_log')->where("id",$post['id'])->find();
            if(empty($order)){
                $this->assign('err_msg','找不到订单信息,请重新充值');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }else if($order['pay_status'] == 1){
                $this->assign('err_msg','找不到订单信息,请重新下单');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }else if(time()-3600>$order["addtime"]){
                $this->assign('err_msg','该订单已过期，请重新菜单');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }
        }
        return ['status'=>1,'msg'=>'找到订单'];
    }

    /**
     * @Author  lignyun
     * @Desc    购买代金券
     */
    public function buy_cash_coupon(){
        $root = request()->domain();
        $post = input('param.');
        $uid = session('_user_uid_.uid');
        $coupon = db('store_coupon')->where('id',$post['id'])->find();
        $data_arr = [
            'order_sn'=>create_order_sn($uid),
            'uid'=>$uid,
            'cat_id'=>$coupon['cat_id'],            //代金券的类型，0通用型
            'cash_coupon_id'=>$post['id'],
            'store_id'=>session('store_id'),
            'pay_time'=>time(),
            'pay_type'=>$post['pay_type'],
            'price'=>$coupon['price'],
            'addtime'=>time(),
            'remark'=>'待支付',
        ];
        //插入支付订单
        db('cash_coupon_list')->insert($data_arr);
        //支付参数
        $params = array(
            'out_trade_no'=>$data_arr['order_sn'],
            'subject'=>'订单支付',
            'total_amount'=>$coupon['price']
//            'total_amount'=>0.01
        );
        $config = config('alipay');     //修改支付宝的回调url地址
        $config['return_url'] = $root."/index.php/index/user/my_coupon";
        $config['notify_url'] = $root."/index.php/index/notify/ali_coupon_notify";
        Pagepay::pay($params,$config);
    }

    /**
     * @Author lignyun
     * @Desc    预支付 -- 检查充值订单
     * 2018-03-21
     */
    private function check_recharge_order($post){
        if(empty($post['order_sn'])){
            $this->assign('err_msg','找不到订单信息，请重新充值');
            $this->assign('err_url',url('User/recharge'));
            $this->assign('err_button','重新充值');
            return $this->fetch('public/error');
            exit();
        }else{
            $order = Db::name('user_wallet_log')->where("order_sn",$post['order_sn'])->find();
            if(empty($order)){
                $this->assign('err_msg','找不到订单信息，请重新充值');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }else if($order['pay_status'] == 1){
                $this->assign('err_msg','该订单已支付，请勿重复支付');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }else if(time()-3600>$order["addtime"]){
                $this->assign('err_msg','该订单已过期，请重新充值');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }
        }
        return ['status'=>1,'msg'=>'找到订单'];
    }


}
